{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## numpy方法读取csv文件(及其他文本文件)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[42 84 79 77 68]\n",
      " [90 60 52 71 91]\n",
      " [46 58 95 89 66]\n",
      " [63 40 43 53 95]\n",
      " [62 67 77 63 62]]\n"
     ]
    }
   ],
   "source": [
    "a = np.random.randint(40,100,size=(5,5))\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. 保存csv文件的方法，使用numpy.savetxt()。可以使用help(np.savetxt)查看详细的使用方法。\n",
    "\n",
    "numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ',......）\n",
    "\n",
    "Parameters\n",
    "    ----------\n",
    "    fname : filename or file handle\n",
    "    X : 1D or 2D array_like\n",
    "        Data to be saved to a text file.\n",
    "    fmt : str or sequence of strs, optional\n",
    "    delimiter : str, optional\n",
    "        String or character separating columns.\n",
    "    header : str, optional。加入数据的标题。\n",
    "    comments : str, optional.标题开始前的字符，默认为Default: '# '\n",
    "    fmt : str or sequence of strs, optional.'%d'表示整型数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "#np.savetxt()函数的实际使用\n",
    "np.savetxt('nprandom.csv',a,fmt='%d',delimiter=',',header='a,b,c,d,e',comments='')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "2. 读取csv文件使用np.loadtxt()方法。可以使用help(np.loadtxt)查看参数说明。\n",
    "\n",
    "Parameters\n",
    "    ----------\n",
    "    fname : file, str, or pathlib.Path\n",
    "    dtype : data-type, optional。读取出数据的数据类型。\n",
    "    comments : str or sequence of str, optional\n",
    "    delimiter : str, optional。被读取文件的分割符\n",
    "    skiprows : int, optional。跳过多少行转换数据类型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[42 84 79 77 68]\n",
      " [90 60 52 71 91]\n",
      " [46 58 95 89 66]\n",
      " [63 40 43 53 95]\n",
      " [62 67 77 63 62]]\n"
     ]
    }
   ],
   "source": [
    "#np.loadtxt()函数的实际使用\n",
    "b=np.loadtxt('nprandom.csv',dtype=np.int8,delimiter=',',skiprows=1)\n",
    "print(b)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "3. numpy特有的存储数据方法。numpy.load(),numpy.save()."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1, 1, 0, 5],\n",
       "       [7, 8, 4, 2],\n",
       "       [2, 6, 6, 2]])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr=np.random.randint(0,9,size=(3,4))\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "#np.save()函数将数组保存成.npy格式的文件。\n",
    "'''\n",
    "save(file, arr, allow_pickle=True, fix_imports=True)\n",
    "    Save an array to a binary file in NumPy ``.npy`` format.\n",
    "    \n",
    "    Parameters\n",
    "    ----------\n",
    "    file : file, str, or pathlib.Path\n",
    "    arr : array_like\n",
    "        Array data to be saved.\n",
    "'''\n",
    "#文件名参数不需要写文件后缀名，函数在保存文件时自动补全。\n",
    "np.save('numpy_doc',arr)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1, 1, 0, 5],\n",
       "       [7, 8, 4, 2],\n",
       "       [2, 6, 6, 2]])"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#np.load()函数从.npy文件中读取数组数据\n",
    "'''\n",
    "load(file, mmap_mode=None, allow_pickle=False, fix_imports=True, encoding='ASCII')\n",
    "    Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files.  \n",
    "    Parameters\n",
    "    ----------\n",
    "    file : file-like object, string, or pathlib.Path\n",
    "        The file to read. File-like objects must support the\n",
    "        ``seek()`` and ``read()`` methods. Pickled files require that the\n",
    "        file-like object support the ``readline()`` method as well.\n",
    "'''\n",
    "arr1=np.load('numpy_doc.npy')\n",
    "arr1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function savetxt in module numpy:\n",
      "\n",
      "savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\\n', header='', footer='', comments='# ', encoding=None)\n",
      "    Save an array to a text file.\n",
      "    \n",
      "    Parameters\n",
      "    ----------\n",
      "    fname : filename or file handle\n",
      "        If the filename ends in ``.gz``, the file is automatically saved in\n",
      "        compressed gzip format.  `loadtxt` understands gzipped files\n",
      "        transparently.\n",
      "    X : 1D or 2D array_like\n",
      "        Data to be saved to a text file.\n",
      "    fmt : str or sequence of strs, optional\n",
      "        A single format (%10.5f), a sequence of formats, or a\n",
      "        multi-format string, e.g. 'Iteration %d -- %10.5f', in which\n",
      "        case `delimiter` is ignored. For complex `X`, the legal options\n",
      "        for `fmt` are:\n",
      "    \n",
      "        * a single specifier, `fmt='%.4e'`, resulting in numbers formatted\n",
      "          like `' (%s+%sj)' % (fmt, fmt)`\n",
      "        * a full string specifying every real and imaginary part, e.g.\n",
      "          `' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej'` for 3 columns\n",
      "        * a list of specifiers, one per column - in this case, the real\n",
      "          and imaginary part must have separate specifiers,\n",
      "          e.g. `['%.3e + %.3ej', '(%.15e%+.15ej)']` for 2 columns\n",
      "    delimiter : str, optional\n",
      "        String or character separating columns.\n",
      "    newline : str, optional\n",
      "        String or character separating lines.\n",
      "    \n",
      "        .. versionadded:: 1.5.0\n",
      "    header : str, optional\n",
      "        String that will be written at the beginning of the file.\n",
      "    \n",
      "        .. versionadded:: 1.7.0\n",
      "    footer : str, optional\n",
      "        String that will be written at the end of the file.\n",
      "    \n",
      "        .. versionadded:: 1.7.0\n",
      "    comments : str, optional\n",
      "        String that will be prepended to the ``header`` and ``footer`` strings,\n",
      "        to mark them as comments. Default: '# ',  as expected by e.g.\n",
      "        ``numpy.loadtxt``.\n",
      "    \n",
      "        .. versionadded:: 1.7.0\n",
      "    encoding : {None, str}, optional\n",
      "        Encoding used to encode the outputfile. Does not apply to output\n",
      "        streams. If the encoding is something other than 'bytes' or 'latin1'\n",
      "        you will not be able to load the file in NumPy versions < 1.14. Default\n",
      "        is 'latin1'.\n",
      "    \n",
      "        .. versionadded:: 1.14.0\n",
      "    \n",
      "    \n",
      "    See Also\n",
      "    --------\n",
      "    save : Save an array to a binary file in NumPy ``.npy`` format\n",
      "    savez : Save several arrays into an uncompressed ``.npz`` archive\n",
      "    savez_compressed : Save several arrays into a compressed ``.npz`` archive\n",
      "    \n",
      "    Notes\n",
      "    -----\n",
      "    Further explanation of the `fmt` parameter\n",
      "    (``%[flag]width[.precision]specifier``):\n",
      "    \n",
      "    flags:\n",
      "        ``-`` : left justify\n",
      "    \n",
      "        ``+`` : Forces to precede result with + or -.\n",
      "    \n",
      "        ``0`` : Left pad the number with zeros instead of space (see width).\n",
      "    \n",
      "    width:\n",
      "        Minimum number of characters to be printed. The value is not truncated\n",
      "        if it has more characters.\n",
      "    \n",
      "    precision:\n",
      "        - For integer specifiers (eg. ``d,i,o,x``), the minimum number of\n",
      "          digits.\n",
      "        - For ``e, E`` and ``f`` specifiers, the number of digits to print\n",
      "          after the decimal point.\n",
      "        - For ``g`` and ``G``, the maximum number of significant digits.\n",
      "        - For ``s``, the maximum number of characters.\n",
      "    \n",
      "    specifiers:\n",
      "        ``c`` : character\n",
      "    \n",
      "        ``d`` or ``i`` : signed decimal integer\n",
      "    \n",
      "        ``e`` or ``E`` : scientific notation with ``e`` or ``E``.\n",
      "    \n",
      "        ``f`` : decimal floating point\n",
      "    \n",
      "        ``g,G`` : use the shorter of ``e,E`` or ``f``\n",
      "    \n",
      "        ``o`` : signed octal\n",
      "    \n",
      "        ``s`` : string of characters\n",
      "    \n",
      "        ``u`` : unsigned decimal integer\n",
      "    \n",
      "        ``x,X`` : unsigned hexadecimal integer\n",
      "    \n",
      "    This explanation of ``fmt`` is not complete, for an exhaustive\n",
      "    specification see [1]_.\n",
      "    \n",
      "    References\n",
      "    ----------\n",
      "    .. [1] `Format Specification Mini-Language\n",
      "           <https://docs.python.org/library/string.html#format-specification-mini-language>`_,\n",
      "           Python Documentation.\n",
      "    \n",
      "    Examples\n",
      "    --------\n",
      "    >>> x = y = z = np.arange(0.0,5.0,1.0)\n",
      "    >>> np.savetxt('test.out', x, delimiter=',')   # X is an array\n",
      "    >>> np.savetxt('test.out', (x,y,z))   # x,y,z equal sized 1D arrays\n",
      "    >>> np.savetxt('test.out', x, fmt='%1.4e')   # use exponential notation\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(np.savetxt)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 总结：\n",
    "1. numpy.save(),numpy.load()函数可以保存、读取所有的ndarry数据，包括任一维度的数据。\n",
    "2. numpy.savetxt(),numpy.loadtxt()函数可以读取、保存所有一维和二维的数组数据，更高维度的不可以保存。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
